package com.hxc.filter;

import com.hxc.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求url
        HttpServletRequest request = (HttpServletRequest) servletRequest; //请求对象转换
        HttpServletResponse response = (HttpServletResponse) servletResponse; //响应对象转换
        String requestURI = request.getRequestURI(); //资源路径：/login
        StringBuffer requestURL = request.getRequestURL(); //完整路径： http://localhost:8080/login
        System.out.println("requestURI: " + requestURI); // /login
        System.out.println("requestURL: " + requestURL); // http://localhost:8080/login
        // 判断是否是登录请求，如果是，直接放行
        if (requestURI.contains("login")) {
            filterChain.doFilter(request, servletResponse);
            // 需要结束当前请求，否则登陆后会继续往下执行进行校验
            return;
        }
        log.info("不是登录请求,进行校验，请求路径:{}", requestURI);
        // 获取请求头中的令牌,根据前端请求头中的字段名称获取
        String token = request.getHeader("token");
        // 判断是否存在，如果不存在，响应401
        if (token == null) {
            response.setStatus(401);
            log.error("令牌为空");
            // throw new BusinessException("未登录，请先登录!");
            return;
        }
        // 解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("token校验通过：{}",claims);
        } catch (Exception e) {
            response.setStatus(401);
            log.error("令牌解析失败：{}", e.getMessage());
            // throw new RuntimeException("未登录，请先登录!");
            return;
        }
        // 放行
        filterChain.doFilter(request, response);

    }
}
